/**
 * author:Administrator
 * date:2015/8/4
 * desc:for elastic-search study
 */


'use strict';

var Router = require('koa-router');
var config = require('../../../config/config.js');
let daoDispatcher = require('../../../dao/article.js');

console.log('router:' + config.baseUrl + '/v2/article');
var router = new Router({
    prefix: config.baseUrl + '/v2/article'
});
module.exports = router.routes();

/**
 * 添加一个news
 * post /api/v2/article/
 {
    "uid":"xxx",
    "articleId":"xxx",
    "nickName":"xxx",
    "articleContent":"xxx"
 }
 */
router.post('/', function*() {
    let result = yield daoDispatcher.addOne(this.request.inParams);
    this.body = result;
});


/**
 * 添加一个news
 * post /api/v2/article/batch
 [{
    "uid":"xxx",
    "articleId":"xxx",
    "nickName":"xxx",
    "articleContent":"xxx"
  }]
 */
router.post('/batch', function*() {
    let list = this.request.inParams;
    let result = yield daoDispatcher.addMany(list);
    this.body = result;
});

/**
 * 统计article_content字段中的 top(100,eg)项记录
 * get /api/v2/article/termfreq?top=1000
 */
router.get('/termfreq', function*() {
    let field = this.query.field || 'articleContent';
    let topNum = this.query.top;
    if (!topNum) topNum = 100;
    else topNum = Number(topNum);
    let result = yield daoDispatcher.termFreq(field, topNum);
    this.body = result;
});

/**
 * get /api/v2/article/qsearch?q=foo
 */
router.get('/qsearch', function*() {
    let q = this.query.q;
    if (q === undefined) {
        this.status = 400;
        this.body = 'must have q, example get /api/v2/article/qsearch?q=foo';
    }

    let result = yield daoDispatcher.qSearch(q);
    this.body = result;
});

/**
 * delete all doc then rebuild the mapping
 * get /api/v2/article/rebuild
 */
router.get('/rebuild', function*() {
    let result = yield daoDispatcher.reBuild();
    this.body = result;
});

/**
 * delete all doc then rebuild the mapping
 * get /api/v2/article/rebuild
 */
router.get('/cscore', function*() {
    let input = this.query;
    let q = input.q;
    if (q === undefined) {
        this.status = 400;
        this.body = "must have q";
        return;
    }
    let add = input.add ? Number(input.add) : 1;
    let sub = input.sub ? Number(input.sub) : 1;
    let mul = input.mul ? Number(input.mul) : 1;
    let json = {q: q, add: add, sub: sub, mul: mul};
    console.log(json);
    let result = yield daoDispatcher.cScore(json);
    this.body = result;
});
